<?php
namespace app\console\controller;

use think\Build;
use think\Db;
use think\Url;
use think\Cache;
use think\Loader;
use think\Session;
use think\Request;
use think\Exception;
use think\Controller;
use app\client\model\ShopSpecAttr;
use app\console\model\Brand as BrandModel;
use app\client\model\ShopGoods as ShopGoodsModel;
use app\console\model\GoodsType as GoodsTypeModel;
use app\common\trilateral\Classify as ClassifyAlias;
use app\client\model\ShopGoodsSpec as ShopGoodsSpecModel;
use app\client\model\ShopGoodsAttr as ShopGoodsAttrModel;
use app\client\model\ShopGoodsType as ShopGoodsTypeModel;
use app\client\model\ShopGoodsFlag as ShopGoodsFlagModel;

class ShopGoods extends Controller
{

    /*
     * 店铺分类选择
     */
    public function classify()
    {
        // 读取分类店铺商品
        $data = GoodsTypeModel::where(['count' => '1'])->field('id,title,count')->order(['id' => 'asc'])->select();


        return $this->fetch('classify', [
            "mate_title" => '商品分类选择',
            'data'       => $data,
        ]);

    }



    /*
     * 店铺商品列表
     */
    public function index()
    {
        // 获取参数
        $inquire = Request::instance()->param();

        // halt($inquire['orderId']);

        // 搜索条件
        $condition = [];
        $sort = ['sort' => 'asc', 'id' => 'desc'];
        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];
        if (!empty($inquire['shop_class_id'])) $condition['parenTid'] = ['eq', $inquire['shop_class_id']];
        if (!empty($inquire['promotion'])) $condition['promotion'] = ['eq', $inquire['promotion']];
        //if (!empty($inquire['status'])) $condition['status'] = ['eq', $inquire['status']];
         if (!empty($inquire['state'])) $condition['state'] = ['eq', $inquire['state']];
        if (!empty($inquire['orderId'])) $sort = [$inquire['orderId'] => 'asc', 'id' => 'desc'];

        // 读取店铺分类店铺商品
        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count')->select();
        // 读取店铺商品
        $data = ShopGoodsModel::where($condition)->field('auding_time,auding_id,auding_status,id,price,parenTid,sort,sale_number,title,update_time,create_id,create_time,recommend,related,promotion,status,state,inventory_hint,charges,inventory,shop_recommend,goods_id')->order($sort)->paginate(10, false, ['query' => $inquire]);
        return $this->fetch('index', [
            'mate_title'   => '出售中的商品',
            'data'         => $data,
            'classify'     => ClassifyAlias::dimension(Cache::get('goodsType')),
            'shopClassify' => $shopClassify,

        ]);
    }

    /**
     * @return array|mixed|\think\response\View
     * 出库list
     */
    public function chuku()
    {
        $param = Request::instance()->param();
        $data = (new \app\console\model\ShopGoods())->where('id','in','1566,1567')->paginate(10, false, ['query' => $param])->each(function ($item, $key) {
            $item->list = Db::name('shop_spec_attr')->where('goods_id', $item->id)->where('shop_id',0)->select();
            $item->count = count(Db::name('shop_spec_attr')->where('goods_id', $item->id)->where('shop_id',0)->select());
        });

        return view('', ['data' => $data]);
    }

    /**
     * @param $id
     * @return array|mixed|\think\response\View
     * 出库到门店
     */
    public function chuku_shop($id){
        $param = Request::instance()->param();
        if(Request::instance()->isPost()){

           if($param['shop_id'] <=0){
               fail('必须选择门店');
           }
            if($param['count'] <=0){
                fail('出库数量必须大于0');

            }
            $count = count($param['shop_id'])*$param['count'];
           if($count > $param['inventory']){
               fail('出库数量不能大于总库存');
           }
            foreach ($param['shop_id'] as $k => $v){
                $goods_attr = Db::name('shop_spec_attr')->where('goods_id',$param['goods_id'])->where('shop_id',$v)->where('attribute',$param['attribute'])->find();
                if($goods_attr){
                    Db::name('shop_spec_attr')->where('goods_id',$param['goods_id'])->where('shop_id',$v)->where('attribute',$param['attribute'])->setInc('inventory',$param['count']);

                }else{
                    Db::name('shop_spec_attr')->insert([
                        'goods_id' => $param['goods_id'],
                        'shop_id' => $v,
                        'attribute' => $param['attribute'],
                        'inventory' => $param['count']
                    ]);

                }
                Db::name('shop_spec_attr')->where('goods_id',$param['goods_id'])->where('shop_id',0)->where('attribute',$param['attribute'])->setDec('inventory',$param['count']);


            }
            win('出库成功',Url::build('chuku'));
        }

        $shop_list = Db::name('shop')->where('is_delete',1)->where('auding_status',2)->select();
        return view('',['shop_list' => $shop_list]);
    }


    public function ruku($id){
        $param = Request::instance()->param();

        if(Request::instance()->isPost()){
            $goods_attr = Db::name('shop_spec_attr')->where('id',$id)->setInc('inventory',$param['count']);
            if($goods_attr){
                win('入库成功',Url::build('chuku'));
            }

        }
        return view('',[]);
    }

    /*
     * 仓库中的商品
     */
    public function warehouse()
    {
        // 获取参数
        $inquire = Request::instance()->param();

        // 搜索条件
        $condition['state'] = ['eq', '2'];
        $condition['member_id'] = ['eq', Session::get('shop_id')];
        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];
        if (!empty($inquire['shop_class_id'])) $condition['parenTid'] = ['eq', $inquire['shop_class_id']];

        // 读取店铺分类店铺商品
        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count')->select();
        // 读取店铺商品
        $data = ShopGoodsModel::where($condition)->field('id,price,parenTid,sort,sale_number,title,create_time,state')->order(['id' => 'desc'])->paginate(10, false, ['query' => $inquire]);

        return $this->fetch('warehouse', [
            'mate_title'   => '仓库中的商品',
            'data'         => $data,
            'classify'     => ClassifyAlias::dimension(Cache::get('goodsType')),
            'shopClassify' => $shopClassify
        ]);
    }

    /*
     * 违规的商品
     */
    public function violation()
    {
        // 获取参数
        $inquire = Request::instance()->param();

        // 搜索条件
        $condition['status'] = ['eq', '3'];
        $condition['member_id'] = ['eq', Session::get('shop_id')];
        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];
        if (!empty($inquire['shop_class_id'])) $condition['parenTid'] = ['eq', $inquire['shop_class_id']];

        // 读取店铺分类店铺商品
        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count')->select();
        // 读取店铺商品
        $data = ShopGoodsModel::where($condition)->field('id,price,parenTid,sort,sale_number,title,create_time,collect,cause')->order(['id' => 'desc'])->paginate(10, false, ['query' => $inquire]);

        return $this->fetch('violation', [
            'mate_title'   => '违规中的商品',
            'data'         => $data,
            'classify'     => ClassifyAlias::dimension(Cache::get('goodsType')),
            'shopClassify' => $shopClassify
        ]);
    }

    /*
     * 店铺分类联动选择
     */
    public function linkage()
    {
        $parenTid = Request::instance()->param('parenTid');
        if (!empty($parenTid))
            return GoodsTypeModel::where(['parenTid' => $parenTid])->field('id,count,title')->order(['id' => 'asc'])->select();
        else
            return false;
    }


    /*
     * 店铺商品添加
     */
    public function create()
    {

        if (Request::instance()->isPost()) {

            $data = Request::instance()->param();

            // 验证
            $validate = Loader::validate('ShopGoods','validate',false,'client');
            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            $model = new ShopGoodsModel();

            // 提交数据
            $dispose = $model->allowField(true)->save($data);

            if (!empty($data['nameAttr'])) {
                // 一对多添加数组
                $flagArr = [];

                for ($i = 0; $i < count($data['nameAttr']); $i++) {
                    $flagArr[$i]['goods_id'] = $model->id;
                    $flagArr[$i]['flag_name'] = $data['nameAttr'][$i];
                    $flagArr[$i]['flag_value'] = $data['valueAttr'][$i];
                }

                $model->flagAttr()->saveAll($flagArr);
            }


            if ($dispose) {
                win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));
            }

            fail('操作失败');

        }

        //获取分类id
        $goods_id = Request::instance()->param('goods_id');

        if (empty($goods_id)) throw new Exception('goodsId not empty');


        // 读取店铺分类店铺商品
        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count,sort')->select()->toArray();

        // 读取类别品牌
        $brand = BrandModel::all();

        // 读取店铺规格
        $attr = ShopGoodsSpecModel::where('goods_type_id' ,['like', '%,' . $goods_id . ',%'],['eq',''],'or')->fetchSql(false)->where('auding_status',2)->where('is_delete',1)->select();

//        foreach ($attr as &$value) {
//            // 获取attr参数
//            $value['attribute'] = ShopGoodsAttrModel::where(['spec_id' => $value['id'], 'goods_type_id' => $goods_id,'or'])->select();
//        }
        foreach ($attr as &$value) {
            // 获取attr参数
            ////$value['attribute'] = ShopGoodsAttrModel::where('spec_id','eq',$value['id'])->where('goods_type_id',['eq',$goods_id],['eq',0],'or')->select();
            $value['attribute'] = ShopGoodsAttrModel::where(['spec_id' => $value['id'], 'goods_type_id' => $goods_id])->select();
            //$value['attribute'] = ShopGoodsAttrModel::where('spec_id',['eq',$value['id']], 'goods_type_id',['eq',$goods_id],'or')->select();
        }
        $shop = Db::name('shop')->where('auding_status',2)->where('is_delete',1)->select();

        return $this->fetch('create', [
            "mate_title"   => '店铺商品添加',
            'shopClassify' => ClassifyAlias::dimension($shopClassify),
            'brand'        => $brand,
            'attr'         => $attr,
            'shop' => $shop
        ]);

    }


    /*
     * 库存中的商品编辑
     */
    public function compiler($id)
    {
        if (Request::instance()->isPost()) {

            $data = Request::instance()->param();

            // 验证
            $validate = Loader::validate('ShopGoods');
            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            $model = new ShopGoodsModel();

            // 提交数据
            $dispose = $model->allowField(true)->save($data, ['id' => $id]);

            if (!empty($data['nameAttr'])) {
                // 一对多添加数组
                $flagArr = [];

                for ($i = 0; $i < count($data['nameAttr']); $i++) {

                    if (!empty($data['flag_id'][$i])) {
                        $flagArr[$i]['id'] = $data['flag_id'][$i];
                    }
                    $flagArr[$i]['goods_id'] = $id;
                    $flagArr[$i]['flag_name'] = $data['nameAttr'][$i];
                    $flagArr[$i]['flag_value'] = $data['valueAttr'][$i];
                }

                (new ShopGoodsFlagModel())->saveAll($flagArr);
            }

            if ($dispose) {
                win('操作成功', Url::build('ShopGoods/warehouse', ['orderId' => 'sort']));
            }

            fail('操作失败');

        }

        //获取分类id
        $goods_id = Request::instance()->param('goods_id');

        // 读取数据
        $item = ShopGoodsModel::get($id);

        $item['spec_attr'] = ShopSpecAttr::where(['goods_id' => $id])->select();

        if (empty($goods_id)) $goods_id = $item['goods_id'];;


        // 读取店铺属性
        $attr = ShopGoodsSpecModel::where(['member_id' => Session::get('shop_id'), 'goods_type_id' => ['like', '%,' . $goods_id . ',%']])->where('auding_status',2)->where('is_delete',1)->select();

        foreach ($attr as &$value) {
            // 获取attr参数
            //$value['attribute'] = ShopGoodsAttrModel::where(['spec_id' => $value['id'], 'goods_type_id' => $goods_id])->select();
            $value['attribute'] = ShopGoodsAttrModel::where(['spec_id' => $value['id'], 'goods_type_id' => $goods_id])->select();
        }


        // 读取店铺分类店铺商品
        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count')->select()->toArray();

        // 读取类别品牌
        $brand = BrandModel::all();

        // 读取商品规格
        $flag_list = ShopGoodsFlagModel::all(['goods_id' => $id]);

        return $this->fetch('create', [
            "mate_title"   => '店铺商品编辑',
            'shopClassify' => ClassifyAlias::dimension($shopClassify),
            'brand'        => $brand,
            'attr'         => $attr,
            'item'         => $item,
            'flag_list'    => $flag_list

        ]);
    }




    /*
     * 店铺商品删除
     */
    public function destroy()
    {

        $id = Request::instance()->param('id');

        // 如果有购买中的商品
        $buy = Db::view('member_order_attached', 'goods_id,shop_order_number')
            ->view('member_order', 'shop_order_number,status', 'member_order.shop_order_number = member_order_attached.shop_order_number')
            ->where(['goods_id' => $id, 'status' => ['in', '1,2,6']])
            ->find();

        if (!empty($buy)) fail('该商品还有未收货或未退款的,请先处理');

        // 启动事务
        Db::startTrans();
        try {

            // 删除商品
            Db::name('shop_goods')->where(['id' => $id])->delete();

            // 删除收藏中的该商品
            Db::name('member_collect')->where(['type_id' => '1', 'collect_id' => $id])->delete();

            // 删除浏览记录
            Db::name('member_browse')->where(['goods_id' => $id])->delete();

            // 删除限时抢购表
            Db::name('limited')->where(['goods_id' => $id])->delete();

            // 删除商品套餐表
            $find = Db::view('shop_goods_combo_selected', 'combo_id,goods_id')
                ->view('shop_goods_combo', 'id', 'shop_goods_combo.id = shop_goods_combo_selected.combo_id')
                ->where(['goods_id' => $id])
                ->find();

            if (!empty($find)) {
                Db::view('shop_goods_combo_selected', 'combo_id,goods_id')
                    ->view('shop_goods_combo', 'id', 'shop_goods_combo.id = shop_goods_combo_selected.combo_id')
                    ->where(['goods_id' => $id])
                    ->delete();
            }

            // 删除商品评价表
            Db::name('shop_goods_evaluate')->where(['goods_id' => $id])->delete();

            // 删除属性关联表
            Db::name('shop_spec_attr')->where(['goods_id' => $id])->delete();

            // 删除促销活动表
            Db::name('promotion')->where(['goods_id' => ['in', $id]])->delete();

            // 提交事务
            Db::commit();

            win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));

        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();

            win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));
        }

        // if (ShopGoodsModel::destroy($id)) {
        //     win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));
        // }
        //
        // fail('操作失败');

    }

    /*
     * 店铺商品编辑
     */
    public function update($id)
    {

        if (Request::instance()->isPost()) {

            $data = Request::instance()->param();
            if(!Request::instance()->param('sp_val/a')){
                fail('请添加商品规格');
            }
            // 验证
            $validate = Loader::validate('ShopGoods','validate',false,'client');
            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            $model = new ShopGoodsModel();

            // 提交数据
            $dispose = $model->allowField(true)->save($data, ['id' => $id]);

            if (!empty($data['nameAttr'])) {
                // 一对多添加数组
                $flagArr = [];

                for ($i = 0; $i < count($data['nameAttr']); $i++) {

                    if (!empty($data['flag_id'][$i])) {
                        $flagArr[$i]['id'] = $data['flag_id'][$i];
                    }
                    $flagArr[$i]['goods_id'] = $id;
                    $flagArr[$i]['flag_name'] = $data['nameAttr'][$i];
                    $flagArr[$i]['flag_value'] = $data['valueAttr'][$i];
                }

                (new ShopGoodsFlagModel())->saveAll($flagArr);
            }

            if ($dispose !== false) {
                win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));
            }

            fail('操作失败');

        }

        //获取分类id
        $goods_id = Request::instance()->param('goods_id');

        // 读取数据
        $item = ShopGoodsModel::get($id);

        $item['spec_attr'] = ShopSpecAttr::where(['goods_id' => $id])->where('shop_id',0)->select();

        if (empty($goods_id)) $goods_id = $item['goods_id'];

        // 读取店铺属性
        $attr = ShopGoodsSpecModel::where('goods_type_id' ,['like', '%,' . $goods_id . ',%'],['eq',''],'or')->fetchSql(false)->where('auding_status',2)->where('is_delete',1)->select();

        foreach ($attr as &$value) {
            // 获取attr参数
          $value['attribute'] = ShopGoodsAttrModel::where('spec_id','eq',$value['id'])->where('goods_type_id',['eq',$goods_id],['eq',0],'or')->select();
            //$value['attribute'] = ShopGoodsAttrModel::where('spec_id',['eq',$value['id']], 'goods_type_id',['eq',''])->select();
        }

        //halt($attr->toArray());
        // 读取店铺分类店铺商品
        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count,sort')->select()->toArray();


        // 读取商品规格
        $flag_list = ShopGoodsFlagModel::all(['goods_id' => $id]);

//        $attr[1] = [
//            ['id' => 1,'goods_type_id' => ',2901,','member_id' => 0,'title' => '门店1','attribute' => [
//                'id' => '2240','goods_type_id' => 2901,'spec_id' => 1, 'title' => '原形'
//                ]
//            ]
//        ];
        //halt($attr->toArray());
        $shop = Db::name('shop')->where('auding_status',2)->where('is_delete',1)->select();
        $r = '';
        $d_shop = Db::name('shop_spec_attr')->field('DISTINCT shop_id')->where('goods_id',$id)->select()->toArray();
        $instr = [];
        if($d_shop){
            foreach ($d_shop as $k => $v){
                $instr[] = $v['shop_id'];
            }
            $r = implode(",",$instr);

        }
        $inventory_sum = Db::name('shop_spec_attr')->where('goods_id',$id)->sum('inventory');
        return $this->fetch('create', [
            "mate_title"   => '店铺商品编辑',
            'shopClassify' => ClassifyAlias::dimension($shopClassify),
            'attr'         => $attr,
            'd_shop' => $r,
            'item'         => $item,
            'shop' => $shop,
            'inventory_sum' => $inventory_sum,
            'flag_list'    => $flag_list

        ]);
    }

    public function inv(){
        $param = Request::instance()->param('shop_id');
        $goods_id = Request::instance()->param('goods_id');
        $data = Db::name('shop_spec_attr')->where('shop_id','in',$param)->where('goods_id',$goods_id)->column('inventory');
        return json_encode($data);
    }
    public function invv(){
        $param = Request::instance()->param('shop_id');
        $goods_id = Request::instance()->param('goods_id');
        $data = Db::name('shop_spec_attr')->where('shop_id','in',$param)->where('goods_id',$goods_id)->column('');
        return json_encode($data);
    }

    public function kc(){
        $shop_id = Request::instance()->param('shop_id');
        $attr = Request::instance()->param('attr');
        $goods_id = Request::instance()->param('goods_id');
        $data = Db::name('shop_spec_attr')->where('shop_id','in',$shop_id)->where('goods_id',$goods_id)->where('attribute',$attr)->value('inventory');
        return json_encode($data);
    }

    /*
     * 猜你喜欢状态改变
     */
    public function related()
    {
        $id = Request::instance()->param('id');
        $related = ShopGoodsModel::where('id', $id)->value('related') == '1' ? 2 : 1;
        if (ShopGoodsModel::where('id', $id)->update(['related' => $related])) {
            return $related;
        }
        return false;
    }

    /*
     * 店铺促销状态
     */
    public function auditing()
    {
        $id = Request::instance()->param('id');
        $recommend = ShopGoodsModel::where('id', $id)->value('recommend') == '1' ? 2 : 1;
        if (ShopGoodsModel::where('id', $id)->update(['recommend' => $recommend])) {
            return $recommend;
        }
        return false;
    }

    /*
     * 促销状态改变
     */
    public function shop_recommend()
    {
        $id = Request::instance()->param('id');
        $promotion = ShopGoodsModel::where('id', $id)->value('state') == '1' ? 2 : 1;
        if (ShopGoodsModel::where('id', $id)->update(['state' => $promotion])) {
            return $promotion;
        }
        return false;
    }

    /*
     * 上架状态改变
     */
    public function dispose_state()
    {
        $id = Request::instance()->param('id');
        $state = ShopGoodsModel::where('id', $id)->value('state') == '1' ? 2 : 1;
        if (ShopGoodsModel::where('id', $id)->update(['state' => $state])) {
            return $state;
        }
        return false;
    }

    /*
     * 上架状态改变
     */
    public function putAway()
    {
        $id = Request::instance()->param('id');
        $state = ShopGoodsModel::where('id', $id)->value('state') == '1' ? 2 : 1;
        if (ShopGoodsModel::where('id', $id)->update(['state' => $state])) {
            return $state;
        }
        return false;
    }

    /*
     * 排列顺序
     */
    public function sorting()
    {

        $id = Request::instance()->param('orderId/a');
        $sort = Request::instance()->param('sort/a');

       if($id){
           foreach ($id as $key => $value) {
               ShopGoodsModel::where('id', $value)->update(['sort' => $sort[$key]]);
           }
       }

        win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));
    }

    /*
     * 上传组图
     */

}
